package com.yuzhi.framework.handler.geometry;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class GeometryFieldInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];
        BoundSql originalBoundSql = mappedStatement.getBoundSql(parameter);

        String originalSql = originalBoundSql.getSql();
        if (originalSql.contains("geometry = ?")) {
            String newSql = originalSql.replace("geometry = ?", "geometry = ST_GeomFromText(?)");

            BoundSql newBoundSql = new BoundSql(
                    mappedStatement.getConfiguration(),
                    newSql,
                    originalBoundSql.getParameterMappings(),
                    originalBoundSql.getParameterObject()
            );

            MappedStatement newMappedStatement = new MappedStatement.Builder(
                    mappedStatement.getConfiguration(),
                    mappedStatement.getId(),
                    boundSql -> newBoundSql,
                    mappedStatement.getSqlCommandType()
            ).build();

            invocation.getArgs()[0] = newMappedStatement;
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}